<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\amqp\CommunityLevelQueue;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\cache\Queue;
use Doraemon\model\AdminAccount\AdminAccount;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\AdmNoteFeature;
use Doraemon\model\AdmNoteOutlineLog;
use Doraemon\model\AdmNoteRemark;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\Content\ContentRelatedCategory as mContentRelatedCategory;
use Doraemon\model\ContentSignExtend as PhotosExtend;
use Doraemon\model\DecorationTask\UserTaskDiary;
use Doraemon\model\Es\UserPortrait;
use Doraemon\model\Member;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\Sysmsg;
use Doraemon\model\Task\TaskBase;
use Doraemon\model\Task\UserTaskInfo as mUserTaskInfo;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\AdmNote;
use Doraemon\service\Circle\PhotosCircle;
use Doraemon\service\Content\ContentRelatedCategory;
use Doraemon\service\Content\ContentRelatedCategory as sContentRelatedCategory;
use Doraemon\service\ContentCategory;
use Doraemon\service\Creators\LevelStandard as sLevelStandard;
use Doraemon\service\DecorationTask\Read;
use Doraemon\service\IntelligentRecommend\HaveRecommend;
use Doraemon\service\Note\NoteHandle;
use Doraemon\service\Photos;
use Doraemon\service\Task\Task as sTask;
use Doraemon\service\User;
use Doraemon\service\UserGrowth\AutoAction;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\Creator\GrowthConfig as tGrowthConfig;
use Doraemon\tools\Filter;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Ip;
use Doraemon\tools\Log;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Frieza\Modules\Photo\Extensions\Filter as SearchFilter;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\cache\FeaturePool as cFeaturePool;
use Doraemon\cache\MachineQuality as cMachineQuality;
use Doraemon\model\Topic\TopicActivity;

class PhotoCheckController extends Controller
{
    const PAGE_SIZE = 20;

    const MARKTAG_FILE = '/home/adm_rsync_dir/mark_tag.json';

    const ES_BUSINESS = [
        "NOT_BUSINESS" => 0,
        "SOFT_BUSINESS" => 1,
        "HARD_BUSINESS" => 2
    ];


    public function index(Request $request, Content $content)
    {
        $searchResult = SearchFilter::getSearchResultByParams($request);
        $total = $searchResult['total'];
        $ids = $searchResult['rows'];
//        $ids =['000d9tp00005c7mb','000d9tq00000098d','000d9tr00000098d'];
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息
        // 获取装修日记
        $diaryList = $diaryIds = $circleList = $circleIds = [];
        foreach ($photos as $photo) {
            if ($photo['type'] == dbPhoto::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
            if ($photo['type'] == dbPhoto::TYPE_CIRCLE) {
                $circleIds[] = $photo['id'];
            }
        }

        if ($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }
        if ($circleIds) {
            $circleList = PhotosCircle::selectPhotoCircle($circleIds);
        }

        //用户信息
        $uids = empty($photos) ? [] : array_column($photos, 'uid');
        $user_infos = Member::getUserInfoByIds($uids);
        $user_infos_regular = [];
        if ($user_infos && is_array($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_infos_regular[$user_info['uid']] = $user_info;
            }
        }

        //用户等级信息
        $user_levels = UserPortrait::getUserLevelByUIds(array_values(array_unique($uids)));
        //特征信息
        $features = AdmNoteFeature::getFeatureByIds($ids);
        $features_arr = [];
        if ($features && is_array($features)) {
            foreach ($features as $features_info) {
                $features_arr[$features_info['note_id']][] = $features_info['feature'];
            }
        }
        $features_regular = [];
        if ($features_arr && is_array($features_arr)) {
            foreach ($features_arr as $note_id => $feature) {
                $features_regular[$note_id] = implode(',', $feature);
                $features_regular[$note_id] = array_unique(explode(',', $features_regular[$note_id]));
                $features_regular[$note_id] = implode(',', $features_regular[$note_id]);
            }
        }

        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        //获取社区特征分类
        $categoryList = sContentRelatedCategory::getTypesByObjIds($ids);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 0, 0);
        // 获取note关联的wiki
        $wiki_map = Photos::getWikiListMapByIds($ids);
        //获取扩展信息
        $extend_map = [];
        $extend_info = PhotosExtend::getExtendInfoByNoteIds($ids);
        if ($extend_info && is_array($extend_info)) {
            foreach ($extend_info as $value) {
                $extend_map[$value['obj_id']] = $value;
            }
        }
        if ($ids) {
            $machineQuality = cMachineQuality::getItems($ids); // 获取机器打分信息
        }

        $i = 1;
        foreach ($photos as &$info) {
            $info['photo_id'] = $info['id'];
            $categoryFirstId = 0;
            $categorySecondId = 0;
            $categorySource = 2;
            if (isset($categoryList[$info['photo_id']])) {
                $cateInfo = $categoryList[$info['photo_id']];
                $categoryFirstField = 'category_first_id';
                $categorySecondField = 'category_second_id';
                if ($cateInfo['source'] == 1) {//机器
                    $categoryFirstField = 'machine_category_first_id';
                    $categorySecondField = 'machine_category_second_id';
                    $categorySource = 1;
                }
                $categoryFirstId = $categoryList[$info['photo_id']][$categoryFirstField];
                $categorySecondId = $categoryList[$info['photo_id']][$categorySecondField];
            }

            $info['id'] = $i;
            $info['user_info'] = $user_infos_regular[$info['uid']];
            $info['admin_like'] = (string)$admin_likes[$info['photo_id']];
            $info['remark'] =  $this->highLight($info['remark']);
            $info['features'] = $features_regular[$info['photo_id']];
            $info['user_levels'] = $user_levels[$info['uid']];
            $info['category_first'] = $categoryFirstId;
            $info['category_second'] = $categorySecondId;
            $info['category_source'] = $categorySource;
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo, $wiki_map[$info['photo_id']]['list']);
            } else {
                $picInfos = json_decode($info['pic_list'], true) ?: [];
                $info['expand'] = $this->_getPicExpand($picInfos, $wiki_map[$info['photo_id']]['list']);
            }
            $info['expand'] .= $this->_getDivLine();
            if ($info['type'] == dbPhoto::TYPE_DIARY) {
                $info['title'] = !empty($info['title']) ? $info['title'] . "---". $diaryList[$info['photo_id']]['title'] : $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($info['type'] == dbPhoto::TYPE_CIRCLE) {
                $info['name'] = $circleList[$info['photo_id']]['circle_name'];
                $info['task_id'] = $circleList[$info['photo_id']]['circle_id'];
            }
            $info['is_business'] = $extend_map[$info['photo_id']]['is_business'] ?: 0;
            $info['display_business'] = $extend_map[$info['photo_id']]['is_display_business'] ?: 0;
            $info['machine_recognition'] = $machineQuality[$info['photo_id']]??0;
            $i++;
        }

        $options = [
            'perPage' => $request->input('per_page') ?: 20
        ];
        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($categoryLabelAll) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->tools(function ($tools) {
                $tools->append("<a href='index/extra' class='btn btn-sm btn-adn' style='float: right;margin-left:5px;'>
<i class='fa fa-delicious'>&nbsp;&nbsp;批量普通未打分note</i></a>");
                $tools->append("<a href='marktag' class='btn btn-sm btn-success' style='float: right;'><i class='fa fa-save'>&nbsp;&nbsp;编辑常用特征</i></a>");
            });
            $grid->filter(function (Grid\Filter $filter) {
                SearchFilter::getFilter($filter);
            });

            $grid->column('photo_id', 'NOTE_ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('admin_like', '额外信息')->display(function () {
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-note-id='$this->photo_id' id='like$this->photo_id'>点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-note-id='$this->photo_id' id='like$this->photo_id'>$this->admin_like 已赞</a>";
                    }
                }
                $detail = "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >图片详情</a><br>";
                $log = "<a href='/admin/photo/photoAuditLog?&id=$this->photo_id' target='_blank' >审核日志</a><br>";
                $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->photo_id' >复制链接</a>";
                // 一部分员工，是兼职，但又得有正式员工的权限
                if (Admin::user()->isRole('partime.user') && !Admin::user()->can('part_time.business')) {
                    if ($like_btn) {
                        return $detail . $log . $like_btn . "<br><br>" . $copy_btn;
                    }
                    return $detail . $log . "<br><br>" . $copy_btn;
                }
                if ($this->is_business) {
                    $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                } else {
                    $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                }
                if ($this->display_business) {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-success addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                } else {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-default addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                }

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
            })->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . nl2br($this->remark);
            })->width(350);

            $grid->column('relation', '关联信息')->display(function () {
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                if ($this->type == dbPhoto::TYPE_DIARY) {
                    return "内容主体：装修日记 <br> 日记id：{$this->task_id} <br>发布时间：{$addtime}";
                } else if ($this->type == dbPhoto::TYPE_CIRCLE) {
                    return "内容主体：圈子内容 <br> 圈子id：{$this->task_id} <br> 圈子名称：{$this->name} <br>发布时间：{$addtime}";
                } else {
                    return "内容主体：图片<br>发布时间：$addtime";
                }
            })->width(150);
            $grid->column('admin_score', '打分')->display(function () {
                // primary
                $class_normal = 'btn-defalut';
                $class_great = 'btn-defalut';
                $class_bad = 'btn-defalut';
                $class_best = 'btn-defalut';
                $common = $this->machine_recognition ? 'btn-primary' : 'btn-success';
                if ($this->admin_score <= 30 && $this->admin_score > 20) {
                    $class_normal = $common;
                } else if ($this->admin_score > 30 && $this->admin_score < 80) {
                    $class_great = $common;
                } else if ($this->admin_score < 6 && $this->admin_score > 0) {
                    $class_bad = $common;
                } else if ($this->admin_score >= 80) {
                    $class_best = $common;
                }
                $options_normal = "<button class='btn normal grade $class_normal btn' data-note-id='$this->photo_id' data-score='30' data-quality='" . dbPhoto::QUALITY_ORDINARY . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_ORDINARY] . "</button><br><br>";
                $options_great = "<button class='btn great grade $class_great' data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                $options_best = "<button class='btn best grade $class_best' data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    $options_great = "<button class='btn great grade $class_great addLike' data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                    $options_best = "<button class='btn best grade $class_best addLike' data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                }
                $options_bad = "<button class='btn bad $class_bad' data-note-id='$this->photo_id' data-score='5' data-quality='" . dbPhoto::QUALITY_LOW . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_LOW] . "</button>";

                return $options_normal . $options_great . $options_best . $options_bad;
            });


            $grid->column('category', '品类')->display(function () use ($categoryLabelAll) {
                $optionsFirst = "<p style='display: flex; align-items: center'>一级品类：<span class='un_category' style='height: 18px; width: 18px; text-align: center; line-height: 15px; display: inline-block; cursor: pointer; border-radius: 100%; color: #fff; background-color: #ccc' data-id={$this->photo_id} >x</span></p>";
                $optionsSecondStr = empty($this->category_second) ? '' : '二级品类：';
                $optionsSecond = '<div><p class="category_second_p">' . $optionsSecondStr . '</p><div class="category_second_lable" style="margin-top: 10px">';
                foreach ($categoryLabelAll as $val) {
                    $btn = $this->category_source == 1 ? 'btn-twitter' : 'btn-success';
                    //一级分类组装
                    if ($val['level'] == 1) {
                        $class_success = ($val['id'] == $this->category_first) ? $btn : 'btn-default';
                        $optionsFirst = $optionsFirst . "<button style='display:inline-block;margin:2px;' class='community_category_first btn btn-sm $class_success' data-id='$this->photo_id' data-category-first-id='" . $val['id'] . "' data-category-second-id='" . $this->category_second . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                    //一级分类组装
                    if ($val['p_id'] == $this->category_first && $val['p_id'] != 0) {
                        $class_success = ($val['id'] == $this->category_second) ? $btn : 'btn-default';
                        $optionsSecond = $optionsSecond . "<button style='display:inline-block;margin:2px;' class='community_category_second btn btn-sm $class_success' data-id='$this->photo_id' data-category-second_id='" . $val['id'] . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                }
                $optionsSecond .= '</div></div>';
                return $optionsFirst . $optionsSecond;
            });
        });

        Admin::script($this->gradeScript());
        Admin::script($this->lowScoreScript());
        Admin::script($this->markScript());
        Admin::script($this->imgScript());
        Admin::script($this->adminLike());
        Admin::script(ContentCategory::clickCategoryScript());
        Admin::script(ContentCategory::clickCategoryLableScript(Admin::user()->id));
        Admin::script($this->adminCopy());

        return $content
            ->header('note审核')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);

    }

    //根据一级品类获取二级、筛选联动
    public function getCategoryLabel()
    {
        $pid = \request()->get('q', 0);
        $data = mContentCategoryLabel::getListFormatKey($pid);
        $result = [];
        foreach ($data as $key => $val) {
            $result[] = [
                'id' => $key,
                'text' => $val,
            ];
        }
        return $result;
    }

    //根据一级品类获取二级、筛选联动
    public function getCategoryLabelById()
    {
        $pid = \request()->get('q', 0);
        $objId = \request()->get('obj_id', 0);
        $data = mContentCategoryLabel::getListFormatKey($pid);
        $list = [];
        foreach ($data as $key => $val) {
            $list[] = [
                'id' => $key,
                'text' => $val,
            ];
        }
        $objInfo = mContentRelatedCategory::get('*', ['obj_id' => $objId, 'status' => 1]) ?? ['category_second_id' => 0];
        $data = ['list' => $list, 'obj_info' => $objInfo];
        return response()->json($data);
    }

    public function changeContentCategoryLabel(Request $request)
    {
        $request = $request->all();
        $secondId = $request['second_id'] ?? 0;
        $objId = $request['obj_id'] ?? 0;
        $adminId = $request['admin_id'] ?? 0;
        $firstId = mContentCategoryLabel::getDetailById($secondId)['p_id'] ?? 0;
        if (empty($firstId)) return '';
        $code = sContentRelatedCategory::changeNoteCategory($objId, $firstId, $secondId, $adminId, mContentRelatedCategory::SOURCE_ADMIN);
        $result = ['code' => $code];
        return response()->json($result);
    }

    //重置品类按钮
    public function resetContentCategory(Request $request)
    {
        $request = $request->all();
        $objId = $request['obj_id'] ?? 0;
        if (empty($objId)) response()->json(['code' => 0]);
        $code = sContentRelatedCategory::resetCategory($objId, Admin::user()->id);
        $result = ['code' => $code];
        return response()->json($result);
    }

    //运营点赞
    public function adminLike()
    {
        return <<<SCRIPT
            $('.addLike').click(function() {
                var note_id = $(this).data('note-id');
                $.ajax({type:"get",url:"like/"+note_id,success:function(data){
                    if(data != '') {
                        $('#like'+note_id).html(data+"已点赞");
                        $('#like'+note_id).addClass('btn-success');
                        $('#like'+note_id).css('color','#FFFFFF');
                        $('#like'+note_id).attr('disabled', 'disabled');
                    }
                }});
            });
            
             $('.addDisplayBusiness').click(function() {
                var note_id = $(this).data('note-id');
                console.log($(this).hasClass('addDisplayBusiness'));
                if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"displayBusiness/"+note_id+"/"+type,success:function(data){
                    if(data) {
                    console.log(type)
                       if (type == 'remove'){
                            $('#display'+note_id).removeClass('btn-success');
                            $('#display'+note_id).addClass('btn-default');
                            $('#display'+note_id).css('color','#444');                        
                       }else{
                        $('#display'+note_id).addClass('btn-success');
                        $('#display'+note_id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                      }
             }});
            });  
            
            $('.addBusiness').click(function() {
                var note_id = $(this).data('note-id');
                console.log($(this).hasClass('addBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"business/"+note_id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#business'+note_id).removeClass('btn-success');
                            $('#business'+note_id).addClass('btn-default');
                            $('#business'+note_id).css('color','#444');                        
                       }else{
                        $('#business'+note_id).addClass('btn-success');
                        $('#business'+note_id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });          
SCRIPT;
    }

    public function saveLike($id)
    {
        $rs = '';
        $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
        if ($hasLike) {
            $rs = Admin::user()->find($hasLike['admin_id'])->name;
        } else {
            AutoAction::autoLike($id, AutoAction::SOURCE_ADMIN);
            AdminAccountOperate::addData([
                "operate_type" => AdminAccountOperate::ACCOUNT_TYPE_LIKE,
                "uid" => (int)0,
                "admin_id" => Admin::user()->id,
                "addtime" => date('Y-m-d H:i:s', time()),
                "obj_id" => $id,
                "obj_type" => 0,
                "content" => ''
            ]);
            $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
            if ($hasLike) {
                $rs = Admin::user()->find($hasLike['admin_id'])->name;
            }
            Queue::insertQueue('Photo/afterAudit', [
                'photo_id' => $id
            ]);
        }
        return $rs;
    }

    public function editBusiness($id, $type)
    {
        $info = PhotosExtend::getExtendInfoByNoteIds($id);

        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_business" => PhotosExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = PhotosExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $rs = PhotosExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['SOFT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_business" => PhotosExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = PhotosExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

    public function displayBusiness($id, $type)
    {
        $info = PhotosExtend::getExtendInfoByNoteId($id);
        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_display_business" => PhotosExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = PhotosExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s');
                $rs = PhotosExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['HARD_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_display_business" => PhotosExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = PhotosExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

    /**
     * 指定时间区间，并获得区间内的指定时间
     * @param int $day
     * @param int $start
     * @param int $end
     * @param int $type
     * @return false|int|null
     */
    private function initRandTime($day, $start, $end, $type = 0)
    {
        if (!in_array($type, [
            0,
            1
        ])) {
            return null;
        }

        if ($type === 0) {
            return time() + mt_rand(($start * 3600), ($end * 3600));
        } else {
            return strtotime(date('Y-m-d', strtotime("+$day day"))) + mt_rand($start * 3600, $end * 3600);
        }
    }

    private function _getVideoExpand($videoInfo, $wikiInfos)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));

        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    private function _getPicExpand($picInfos, $wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    private function _getWikiExpand($wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($wikiInfo) {
            return "<div style='display:inline-block;margin:3px;width:220px;height:220px;'>" .
                "<img src='" . $wikiInfo['cover_img'] . "' height='200' class='img' /><br/>" .
                "<a href='https://beerus.haohaozhu.me/admin/wiki/admList/{$wikiInfo['id']}/edit' target='_blank' >{$wikiInfo['basic_title']}</a>" .
                "</div>";

        }, (array)$wikiInfos)));
        $box = new Box('wiki信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function lowScoreScript()
    {
        return <<<SCRIPT
            $('.bad').unbind('click').click(function() {
                var _this = $(this);
                var note_id = $(this).data('note-id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '原因归类',
                    shadeClose: true,
                    shade: 0.9,
                    area: ['700px', '600px'],
                    content: 'lowScore/'+note_id,
                    end: function() {
                        $.ajax({type:"get",url:"poorQuality/"+note_id,success:function(code) {
                            if(code == 1) {
                                _this.addClass('btn-success');
                                _this.siblings('button').removeClass('btn-success');
                                _this.siblings('button').addClass('btn-default');
                            }
                        }})
                    }
                });
		    });
SCRIPT;
    }

    public function poorQuality($noteId)
    {
        $quality = dbPhoto::get('quality', ['id' => $noteId]);
        if ($quality == dbPhoto::QUALITY_LOW) {
            return 1;
        }
        return 0;
    }

    //差级评分原因选择
    public function lowScore(\App\Admin\Extensions\WorkContent $content, $noteId)
    {
        $info = [
            'note_id' => $noteId,
            'reason' => AdmNoteOutlineLog::LOW_REASON_BUSINESS_USERS,
            'quality' => dbPhoto::QUALITY_LOW,
            'score' => 5,
        ];

        $form = new Form($info);
        $form->hidden('note_id');
        $form->hidden('quality', '质量');
        $form->hidden('score', '分数');
        $form->select('reason', '原因')->options(AdmNoteOutlineLog::LOW_REASON_DESC)->required();
        $form->action('/admin/photo/photocheck/setLowGrade');
        $form->disableReset();

        return $content
            ->header('原因归类')
            ->body($form->render());
    }

    private function gradeScript()
    {
        $url = route('photocheck.grade');
        return <<<SCRIPT
            $('.grade').click(function() {
                $(this).addClass('btn-success');
                $(this).siblings('button').removeClass('btn-success');
                $(this).siblings('button').removeClass('btn-primary');
                $(this).siblings('button').addClass('btn-default');
                toastr.success('打分成功', null, {
                    timeOut : 1000
                });
                
                let noteId = $(this).data('note-id');
                let score = $(this).data('score');
                let quality = $(this).data('quality');
                let url = '{$url}'
                let params = {note_id:noteId, score:score, quality:quality}
                $.post(url, params)
            });

SCRIPT;
    }

    public function setGrade(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $note_id = $params['note_id'];
            $source = $params['source'];
            $data = [
                'quality' => $params['quality'],
                'admin_score' => $params['score'],
                'show_status' => dbPhoto::SHOW_STATUS_NORMAL,
                'status' => dbPhoto::STATUS_SUCCESS
            ];
            Log::info('记录打分：', [$data, $params]);

            // 查询更新之前此note的质量
            $photoInfo = Photos::getPhoto($note_id);
            $qualityLastTime = -1;
            if ($photoInfo['quality'] != $params['quality']) {
                $qualityLastTime = $photoInfo['quality'];
            }

            $rs = dbPhoto::updatePhotoById($note_id, $data);
            if ($rs) {
                Log::info('记录打分：', [2, $rs]);
                // 正常情况下，一个内容的质量变更为精选之前它的质量一定是优质。如果一个内容从优质调整为精选/普通/差 就需要从待精选池移除
                if (in_array($params['quality'], [dbPhoto::QUALITY_FEATURED, dbPhoto::QUALITY_ORDINARY])) {
                    cFeaturePool::removeNote($note_id); // 从待精选池中移除
                }
                cMachineQuality::removeMark($note_id); // 人工操作后，移除机打标识


                NoteHandle::remarkNote($note_id, "", 1);
                // 添加到队列，更新搜索图片
                cPhotos::delete($note_id);
                CommunityQueue::insertQueue('queue/photo/editphoto', [
                    'photo_id' => $note_id
                ], CommunityQueue::QUEUE_COMMUNITY);

                // 投入wiki服务队列
                \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', [
                    'obj_id' => $note_id,
                ], \Doraemon\amqp\Queue::QUEUE_BIZ);
                $this->pushLevel3Standard($note_id, $qualityLastTime, $params['quality'], $photoInfo);

                if ($data['quality'] == dbPhoto::QUALITY_FEATURED) {
                    // 判断是否曾经打过精选
                    //log信息
                    $onceFeature = 0;
                    $logs = AdmNoteOutlineLog::getLogsByIds($note_id);

                    if ($logs && is_array($logs)) {
                        foreach ($logs as $log) {
                            if (strpos($log['log'], mPhotos::QUALITY_DESC[$params['quality']]) !== false) {
                                $onceFeature = 1;
                            }
                        }
                    }
                    Log::info('记录打分：', [3, $onceFeature, $logs]);
                    // 如果没有打过精选就发送下行
                    if ($onceFeature == 0) {
                        Log::info('记录打分：', [4, '发送消息和处理限时任务']);
                        $noteInfo = Photos::getNoteInfo($note_id);
                        $this->sendMsg($note_id, $noteInfo); // 发送精选下行
                        $this->performTask($noteInfo); // 处理限时任务
                    }
                }
                $channel = AdmNoteOutlineLog::AUDIT_CHANNEL_NOTE;
                if ($source == 2){
                    $channel = AdmNoteOutlineLog::AUDIT_CHANNEL_OPERATE_FEATURE;
                }
                // log记录
                AdmNote::auditLog($note_id, $params['quality'], Admin::user()->name, $channel);

                $msg = '打分成功';
                //确认品类的标签
                sContentRelatedCategory::changeNoteCategoryAfterGrade($note_id, Admin::user()->id);
            }
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    public function setLowGrade(Request $request)
    {
        $msg = '打分成功';
        try {
            $params = $request->all();
            $note_id = $params['note_id'];
            $reasonType = $params['reason'];

            $data = [
                'quality' => $params['quality'],
                'admin_score' => $params['score']
            ];
            // 如果原因是盗图，那么分发状态是仅自己可见。 否则的话，是私域流量可见
            if (in_array($reasonType, [AdmNoteOutlineLog::LOW_REASON_PIRATE])) {
                $data['show_status'] = dbPhoto::SHOW_STATUS_PRIVATE;
            } else {
                $data['show_status'] = dbPhoto::SHOW_STATUS_PRIVATE_FLOW;
            }
            $data['status'] = dbPhoto::STATUS_REVIEW;

            // 查询更新之前此note的质量
            $photoInfo = Photos::getPhoto($note_id);
            $qualityLastTime = -1;
            if ($photoInfo['quality'] != $params['quality']) {
                $qualityLastTime = $photoInfo['quality'];
            }

            $rs = dbPhoto::updatePhotoById($note_id, $data);

            if ($rs) {
                // 正常情况下，一个内容的质量变更为精选之前它的质量一定是优质。如果一个内容从优质调整为精选/普通/差 就需要从待精选池移除
                cFeaturePool::removeNote($note_id); // 从待精选池中移除
                cMachineQuality::removeMark($note_id); // 人工操作后，移除机打标识
                // 添加到队列，更新搜索图片
                CommunityQueue::insertQueue('queue/photo/editphoto', [
                    'photo_id' => $note_id
                ], CommunityQueue::QUEUE_COMMUNITY);
                NoteHandle::remarkNote($note_id, AdmNoteRemark::REMARK_ALMOST_OUTLINE);
                // log记录
                AdmNote::auditLog($note_id, $params['quality'], Admin::user()->name, AdmNoteOutlineLog::AUDIT_CHANNEL_NOTE, $reasonType);
                // 删除图片信息缓存
                cPhotos::delete($note_id);
                //创作者中心3.0-质量为差
                $this->pushLevel3Standard($note_id, $qualityLastTime, $params['quality'], $photoInfo);
                //note被打上“差”后自动触发下行
                $this->lowGradePush($reasonType, $note_id);
                sContentRelatedCategory::changeNoteCategoryAfterGrade($note_id, Admin::user()->id);
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage();
        }

        $success = new MessageBag([
            'title' => $msg
        ]);
        return back()->with(compact('success'));
    }

    private function sendMsg($noteId, $noteInfo)
    {

        $url = 'https://img.haohaozhu.cn//Op-imageShow//2e9f320ku0af0jK00qwy59u?iv=1';
        //如果note类型为视频
        if ($noteInfo['show_type'] == mPhotos::SHOW_TYPE_VIDEO) {
            $videoInfo = $noteInfo['video_info'];
            if ($videoInfo['new_pic_url']) {
                $picList = [
                    $videoInfo['new_pic_url'],
                    'https://img.haohaozhu.cn/Op-imageShow/8e19d308y04j0Qd00qs07h4?iv=1'
                ];
                $result = \Doraemon\tools\ImageCreate::buildImageByTidAndParams(11, $picList);
                $url = $result['url'];
            }

        } else {
            if ($noteInfo['new_pic_url']) {
                $picList = [
                    $noteInfo['new_pic_url'], // 用户首图
                    'https://img.haohaozhu.cn/Op-imageShow/8e19d308y04j0Qd00qs07h4?iv=1'// 盖章
                ];
                $result = \Doraemon\tools\ImageCreate::buildImageByTidAndParams(11, $picList);
                $url = $result['url'];
            }
        }

        Queue::insertQueue('queue/Sysmsg/Send',
            [
                'msgCode' => 405,
                'to_uid' => IdParse::getUid($noteId),
                'msgParams' => [
                    'note_id' => $noteId,
                    'img' => $url ?: null,
                    'link' => HhzNiceLivingUrl::getNoteDetailLink($noteId),
                ]
            ], Queue::QUEUE_DORAEMON
        );
    }

    private function performTask($noteInfo)
    {
        $topicRelatedTask = file_get_contents('/home/adm_rsync_dir/limit_time_task.json');
        $topicRelatedTask = $topicRelatedTask ? json_decode($topicRelatedTask, true) : [];
        $topicIdList = array_keys($topicRelatedTask);
        Log::info('记录打分：', [5, $noteInfo, $topicRelatedTask, $topicIdList]);
        if (!$noteInfo['topic']['id']) {
            // 基于话题id查询话题标题
            $topicList = TopicActivity::getByIds($topicIdList, ['id','title']);
            $topicList = array_column($topicList, null, 'title');
            $topicTitle = array_column($topicList, 'title');
            // 提取内容中的轻话题
            $tagList = Photos::showTag($noteInfo['remark']);
            $tagList = array_column($tagList, 'title');
            // 提取轻话题交集
            $intersectTopicList = array_intersect($topicTitle, $tagList);
            Log::info('记录打分：', [6, $noteInfo, $intersectTopicList, $tagList, $topicTitle]);
            if ($intersectTopicList) {
                $intersectTopicIdList = [];
                foreach ($intersectTopicList as $topic) {
                    $intersectTopicIdList[] = $topicList[$topic]['id'];
                }
                Log::info('记录打分：', [7, $noteInfo, $intersectTopicIdList]);
                if ($intersectTopicIdList) {
                    foreach ($intersectTopicIdList as $intersectTopicId) {
                        if ($topicRelatedTask[$intersectTopicId]['has_wiki'] && $noteInfo['has_goods'] == 0) {
                            return;
                        }
                        $uid = IdParse::getUid($noteInfo['id']);
                        $taskId = $topicRelatedTask[$intersectTopicId]['task_id'];
                        // 基于任务id查询当前任务的完成度。如果当前任务正在进行中的，并且handle之后为已完成的话，需要发送下行。
                        $hasTaskId = TaskBase::getInfo(['start_time[<]' => time(), 'end_time[>]' => time(), 'id' => $taskId], 'id');
                        Log::info('记录打分：', [8, $noteInfo, $uid, $hasTaskId]);
                        if ($hasTaskId) {
                            $taskInfo = mUserTaskInfo::getInfo(['uid' => $uid, 'task_id' => $taskId]);
                            $result = sTask::handleTask($uid, $taskId);
                            Log::info('记录打分：', [9, $noteInfo, $uid, $hasTaskId, $result]);
                            if ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_STARTING && $result['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) {
                                // 发送下行
                                Queue::insertQueue('queue/Sysmsg/Send',
                                    [
                                        'msgCode' => 413,
                                        'to_uid' => $uid,
                                        'msgParams' => [
                                            'task_title' => $this->stringTruncated($result['task_title'], 7, 3),
                                            'total' => $taskInfo['total'],
                                        ]
                                    ], Queue::QUEUE_DORAEMON
                                );
                            }
                        }
                    }
                }
            }

        } else {
            if (in_array($noteInfo['topic']['id'], $topicIdList)) {
                if ($topicRelatedTask[$noteInfo['topic']['id']]['has_wiki'] && $noteInfo['has_goods'] == 0) {
                    return;
                }

                $uid = IdParse::getUid($noteInfo['id']);
                $taskId = $topicRelatedTask[$noteInfo['topic']['id']]['task_id'];
                // 基于任务id查询当前任务的完成度。如果当前任务正在进行中的，并且handle之后为已完成的话，需要发送下行。
                $hasTaskId = TaskBase::getInfo(['start_time[<]' => time(), 'end_time[>]' => time(), 'id' => $taskId], 'id');
                if ($hasTaskId) {
                    $taskInfo = mUserTaskInfo::getInfo(['uid' => $uid, 'task_id' => $taskId]);
                    $result = sTask::handleTask($uid, $taskId);
                    if ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_STARTING && $result['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) {
                        // 发送下行
                        Queue::insertQueue('queue/Sysmsg/Send',
                            [
                                'msgCode' => 413,
                                'to_uid' => $uid,
                                'msgParams' => [
                                    'task_title' => $this->stringTruncated($result['task_title'], 7, 3),
                                    'total' => $taskInfo['total'],
                                ]
                            ], Queue::QUEUE_DORAEMON
                        );
                    }
                }
            }
        }
    }

    /**
     * 字符串截断并用指定符号做补充
     * @param $string
     * @param $end
     * @param $length
     * @param string $mode
     * @return string
     */
    private function stringTruncated($string, $end, $length, $mode = '.')
    {
        if ($string) {
            if (strlen($string) <= $end) {
                return $string;
            }
            $repeat = str_repeat($mode, $length);
            return mb_substr($string, 0, $end) . $repeat;
        }
        return '';
    }

    private function lowGradePush($reasonType, $note_id)
    {
        if (in_array($reasonType, [
            AdmNoteOutlineLog::LOW_REASON_SOFT_AD,
            AdmNoteOutlineLog::LOW_REASON_FORBIDDEN,
            AdmNoteOutlineLog::LOW_REASON_WATERMARK,
            AdmNoteOutlineLog::LOW_REASON_QR_CODE,
            AdmNoteOutlineLog::LOW_REASON_EFFECT_PICTURE
        ])) {
            //获取note详情
            $noteInfo = DbPhotos::getPhoto($note_id);
            $noteTitle = $noteInfo['title'] == '' ? '' : '「' . $noteInfo['title'] . '」';
            $noteAddTime = date('Y年m月d日 H:i:s', $noteInfo['addtime']) ?? '';

            $detail = '';
            switch ($reasonType) {
                case AdmNoteOutlineLog::LOW_REASON_SOFT_AD:
                case AdmNoteOutlineLog::LOW_REASON_FORBIDDEN:
                    $detail = '亲爱的住友，你于' . $noteAddTime . '发布的图片' . $noteTitle . '，因含有推广或广告信息，暂不被推荐哟！点击进行修改。如需申诉，可发送邮件到hello@haohaozhu.com';
                    break;
                case AdmNoteOutlineLog::LOW_REASON_WATERMARK:
                case AdmNoteOutlineLog::LOW_REASON_QR_CODE:
                    $detail = '亲爱的住友，你于' . $noteAddTime . '发布的图片' . $noteTitle . '，因含有水印、二维码等违规信息，将仅推荐给粉丝。点击进行修改。如需申诉，可发送邮件到hello@haohaozhu.com';
                    break;
                case AdmNoteOutlineLog::LOW_REASON_EFFECT_PICTURE:
                    $detail = '亲爱的住友，你于' . $noteAddTime . '发布的图片' . $noteTitle . '，因含有效果图，暂不被推荐哟！点击进行修改。如需申诉，可发送邮件到hello@haohaozhu.com';
                    break;
            }

            if ($detail != '') {
                //推送消息
                Queue::insertQueue('queue/Sysmsg/Send',
                    [
                        'msgCode' => 126,
                        'to_uid' => IdParse::getUid($note_id),
                        'msgParams' => [
                            'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
                            'type' => Sysmsg::TYPE_SYS_MSG,
                            'note_id' => $note_id,
                            'detail' => $detail,
                            'link' => HhzNiceLivingUrl::getNoteDetailLink($note_id) ?: null,
                        ]
                    ], Queue::QUEUE_DORAEMON
                );
            }
        }
    }

    private function markScript()
    {
        $url = route('photocheck.mark');
        return <<<SCRIPT
            $('.marktag').click(function() {
                var _this = $(this);
                _this.css('pointer-events','none');
                _this.siblings('button').css('pointer-events','none');
                let noteId = $(this).data('id');
                let tag = $(this).data('tag');
                
                if(_this.hasClass('btn-success')) {
                    
                    var arr = _this.attr('data-had').split(',');
                    var new_had = '';
                    for(var i in arr){
                        if(arr[i] != tag) {
                            new_had = new_had + ',' + arr[i]
                        }
                    }
                    _this.attr('data-had', new_had);
                    _this.siblings('button').attr('data-had', new_had);
                } else {
                    _this.attr('data-had', _this.attr('data-had')+','+tag);
                    _this.siblings('button').attr('data-had', _this.attr('data-had'));
                }
                
                let had_tag = $(this).data('had');
                let url = '{$url}'
                let type = '';
                
                if(_this.hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                
                let params = {note_id:noteId, tag:tag, type:type, had_tag:had_tag}
                
                $.post(url, params, function (e) {
                    if(e.code == 1) {
                        if(_this.hasClass('btn-success')) {
                            _this.removeClass('btn-success');
                            _this.addClass('btn-default');
                            
                        } else {
                            _this.removeClass('btn-default');
                            _this.addClass('btn-success');
                        }
                        toastr.success(e.msg, null, {
                            timeOut : 1000
                        });  
                    } else {
                        toastr.error(e.msg, null, {
                            timeOut : 1000
                        });
                    }
                    setTimeout(function() {
                        _this.css('pointer-events','auto');
                        _this.siblings('button').css('pointer-events','auto');
                    }, 1000);
                   
                    
                });
            });

SCRIPT;
    }

    public function setMark(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $note_id = $params['note_id'];
            $tag = $params['tag'];
            $type = $params['type'];
            $had_tag = $params['had_tag'];
            $features = $had_tag;
            $old_features = AdmNoteFeature::getNoteFeatureByNoteId($note_id, AdmNoteFeature::TYPE_NOTE);
            if ($type == 'add') {
                $features = $old_features[0] . ',' . $tag;
                $features = array_filter(array_unique(explode(',', $features)));
                $features = implode(',', $features);
            } else {

                $features_old = explode(',', $old_features[0]);
                if ($features_old && is_array($features_old)) {
                    foreach ($features_old as $k => $feature) {
                        if ($feature == $tag) {
                            unset($features_old[$k]);
                        }
                    }
                    $features = implode(',', $features_old);
                }

            }

            $old_features_pics = AdmNoteFeature::getNoteFeatureByNoteId($note_id, AdmNoteFeature::TYPE_PIC);

            $data["feature"] = $features;
            $data["note_id"] = $note_id;
            $data["status"] = AdmNoteFeature::STATUS_NORMAL;
            $data["type"] = AdmNoteFeature::TYPE_NOTE;
            if ($old_features && is_array($old_features)) {
                $data["edittime"] = time();
                $rs = AdmNoteFeature::updateDataById($note_id, $data);
            } else {
                $data["obj_id"] = $note_id;
                $data["addtime"] = time();
                AdmNoteFeature::add($data);
            }

            if ($old_features_pics && is_array($old_features_pics)) {
                $data_pic["feature"] = $features;
                $data_pic["edittime"] = time();
                $rs = AdmNoteFeature::updatePicDataById($note_id, $data_pic);
            }

            // 删除图片信息缓存
            cPhotos::delete($note_id);
            Queue::insertQueue('Photo/afterAudit', array(
                'photo_id' => $note_id
            ));

            $msg = '标记成功';


        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    //标记特征页面
    public function markTag(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('note特征')
            ->breadcrumb(
                [
                    'text' => 'note审核列表',
                    'url' => 'photo/photocheck/index'
                ],
                [
                    'text' => 'note特征',
                    'url' => 'photo/photocheck/marktag'
                ]
            )
            ->body($this->listMark($request));
    }

    public function listMark($request)
    {
        $tags = [];
        if (file_exists(self::MARKTAG_FILE)) {
            $tags = (array)json_decode(file_get_contents(self::MARKTAG_FILE), true);
        }
        $gridModel = new pGridDataModel($tags, count($tags), [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableExport();
            $grid->disablePagination();
            $grid->disableRowSelector();

            $grid->column('id');
            $grid->column('mark', '特征词');
            $grid->column('if_show', '是否展示')->replace([
                0 => '隐藏',
                1 => '展示'
            ])->width(150);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
            });

        });

        $list = $listGrid->render();
        return $list;
    }

    //添加特征页面
    public function add(Request $request, Content $content)
    {

        $request = $request->all();
        return $content
            ->header('note审核')
            ->breadcrumb(
                [
                    'text' => 'note特征列表',
                    'url' => 'photo/photocheck/checktag'
                ],
                [
                    'text' => '添加特征',
                    'url' => 'photo/photocheck/checktag/create'
                ]
            )
            ->body(self::editAction($id = 0));

    }

    public function edit(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('note审核')
            ->breadcrumb(
                [
                    'text' => 'note特征列表',
                    'url' => 'photo/photocheck/checktag'
                ],
                [
                    'text' => '添加特征',
                    'url' => 'photo/photocheck/checktag/create'
                ]
            )
            ->body(self::editAction($id));

    }

    public function editAction($id = 0)
    {
        $data = [];

        if ($id != 0) {
            //修改
            $tags = [];
            if (file_exists(self::MARKTAG_FILE)) {
                $tags = (array)json_decode(file_get_contents(self::MARKTAG_FILE), true);
            }
            if ($tags && is_array($tags)) {
                foreach ($tags as $tag) {
                    if ($tag['id'] == $id) {
                        $data = $tag;
                        break;
                    }
                }
            }

            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $form = new Form($data);
        }
        $form->text('mark', '特征词');
        $form->radio('if_show', '是否展示')->options([
            0 => '否',
            1 => '是'
        ]);

        $form->action('/admin/photo/photocheck/marktag/save');

        return $form->render();
    }

    public function editSubmit(Request $request, Content $content)
    {
        $request = $request->all();
        $data = [];
        $rs = false;
        $new_data = [];

        $data['mark'] = $request['mark'];
        $data['if_show'] = $request['if_show'];

        //全部特征信息
        if (file_exists(self::MARKTAG_FILE)) {
            $maxid = 0;
            $tags = json_decode(file_get_contents(self::MARKTAG_FILE), true);
            if ($tags && is_array($tags)) {
                $ids = array_column($tags, 'id');

                $maxid = max($ids);
            }

            if (isset($request['id']) && $request['id']) {
                //修改
                $data['id'] = $request['id'];
                $tags = [];
                if (file_exists(self::MARKTAG_FILE)) {
                    $tags = (array)json_decode(file_get_contents(self::MARKTAG_FILE), true);
                }
                if ($tags && is_array($tags)) {
                    foreach ($tags as $k => $tag) {
                        if ($tag['id'] == $data['id']) {
                            $tags[$k]['id'] = $data['id'];
                            $tags[$k]['mark'] = $request['mark'];
                            $tags[$k]['if_show'] = $request['if_show'];
                        }
                    }
                }

                $rs = file_put_contents(self::MARKTAG_FILE, json_encode($tags, JSON_UNESCAPED_UNICODE));

            } else {
                //添加
                $data['id'] = $maxid + 1;
                $new_data[] = $data;
                $infos = array_merge((array)$tags, $new_data);
                $infos = array_filter(array_values($infos));
                $rs = file_put_contents(self::MARKTAG_FILE, json_encode($infos, JSON_UNESCAPED_UNICODE));
            }
        }

        if ($rs) {
            return redirect('/admin/photo/photocheck/marktag');
        } else {
            return redirect('/admin/photo/photocheck/marktag');
        }

    }

    //note批量普通
    public function extra(Request $request, Content $content)
    {
        return $content
            ->header('未打分note批量普通')
            ->body($this->listAction());
    }

    public function listAction()
    {
        $data = [];
        $data['start'] = date('Y-m-d H:i:s', time() - 1);
        $data['end'] = date('Y-m-d H:i:s', time());

        $form = new Form($data);
        $form->datetimeRange('start', 'end', '按时间段批量设置为普通：')->help('时间段内未打分note,不包括视频,最多一次操作24小时的内容');
        $form->disableReset();
        $form->action('/admin/photo/photocheck/index/savenormalmany');
        return $form->render();
    }

    public function saveNormalMany(Request $request)
    {

        $request = $request->all();
        $start = strtotime($request['start']);
        $end = strtotime($request['end']);
        if (($end - $start) > 86400) {
            $error = new MessageBag([
                'title' => '选择的时间段请不要超过24小时哦',
            ]);
            return redirect('/admin/photo/photocheck/index')->with(compact('error'));
        }
        $photo_infos = dbPhoto::getPhotoInfoByTime($start, $end);
        if ($photo_infos && is_array($photo_infos)) {
            foreach ($photo_infos as $photo_info) {
                if ($photo_info['admin_score'] == 0 && $photo_info['type'] != 2) {
                    $data['admin_score'] = 30;
                    $data['edittime'] = time();
                    $data['quality'] = dbPhoto::QUALITY_ORDINARY;
                    $rs = dbPhoto::updatePhotoById($photo_info['id'], $data);
                    if ($rs) {
                        // 添加到队列，更新搜索图片
                        CommunityQueue::insertQueue('queue/photo/editphoto', [
                            'photo_id' => $photo_info['id']
                        ], CommunityQueue::QUEUE_COMMUNITY);
                        \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', array(
                            'obj_id' => $photo_info['id'],
                        ), \Doraemon\amqp\Queue::QUEUE_BIZ);
                    }
                }
            }
            $success = new MessageBag([
                'title' => '批量操作成功',
            ]);
            return redirect('/admin/photo/photocheck/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '批量操作失败，没有可操作note哦',
            ]);
            return redirect('/admin/photo/photocheck/index')->with(compact('error'));
        }
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }

    //复制H5链接
    public function copyUrl($id)
    {
        return Hhzurl::h5PhotoShow($id);
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }

//    // 投入等级判断队列
//    private function pushLevelStandard($noteId, $qualityLastTime)
//    {
//        CommunityLevelQueue::insertQueue('queue/creators/levelStandard', [
//            'uid' => IdParse::getUid($noteId),
//            'obj_id' => $noteId,
//            'event' => sLevelStandard::EVENT_NOTE_ADMIN_SCORE,
//            'is_join_brand' => sLevelStandard::NOTE_JOIN_BRAND_UNKNOWN,
//            'quality_last_time' => $qualityLastTime,
//            'click_type' => 'system_creators_levelStandard'
//        ], CommunityLevelQueue::QUEUE_COMMUNITY);
//    }
    //创作者中心3.0-创作力Note
    private function pushLevel3Standard($noteId, $oldQuality, $newQuality, $photoInfo)
    {
        $remarks = ['old_quality' => $oldQuality, 'new_quality' => $newQuality];
        CommunityQueue::insertQueue(tGrowthConfig::MQ_QUEUE_URL, [
            'event_name' => tGrowthConfig::CREAT_GROWTH_NOTE,
            'obj_id' => $noteId,
            'uid' => IdParse::getUid($noteId),
            'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
        ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);

        //积分操作-评为精选增加积分
        if ($newQuality == mPhotos::QUALITY_FEATURED) {
            //区分装修日记和普通note
            $eventName = $photoInfo['type'] == mPhotos::TYPE_DIARY ? PointConfig::DIARY_QUALITY_FEATURED : PointConfig::NOTE_QUALITY_FEATURED;
            CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                'event_name' => $eventName,
                'obj_id' => $noteId,
                'uid' => IdParse::getUid($noteId),
                'type' => PointConfig::POINT_AWARD
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
        }
    }

    // 正文中轻话题高亮
    private function highLight($remark)
    {
        preg_match_all('/#([\w\-]{1,15}+)/u', $remark . ' ', $userTags);

        if (isset($userTags[0]) && !empty($userTags[0])) {
            $replaceRemarkArr = [];
            foreach ($userTags[0] as $userTag) {
                $replaceRemarkArr[] = '<b style="color:deepskyblue;">' . $userTag . '</b>';
            }
            return str_replace($userTags[0], $replaceRemarkArr, $remark);
        }

        return $remark;
    }
}